// pages/log/log.js
import { getCode, login } from '../../api/user'
import { validatorMobile, validatorCode } from '../../utils/validators'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // from
    mobile: '',
    code: '',
    // input-err
    flag1: false,
    errMsg1: null,
    falg2: false,
    errMsg2: null,
    // code-loding
    wait: 0
  },

  /**
   * 输入框失焦事件
   */
  // 验证手机
  validateMoblie() {
    const flag = validatorMobile(this.data.mobile)
    if (!flag) {
      this.setData({"flag1": true,"errMsg1": '请输入正确的手机号'})
      return Promise.reject("手机号不正确")
    } else {
      this.setData({"flag1": false,"errMsg1": ''})
    }
  },
  // 验证密码
  validateCode() {
    const flag = validatorCode(this.data.code)
    if (!flag) {
      this.setData({ "flag2": true, "errMsg2": '请输入验证码' })
      return Promise.reject("验证码格式不正确")
    } else this.setData({"flag2": false,"errMsg2": ''})
  },
  // 输入取消验证
  cancelValidate(e) {
    const type = e.currentTarget.dataset.type
    if (type === 'm') {
      this.setData({"flag1": false,"errMsg1": ''})
    } else this.setData({"flag2": false,"errMsg2": ''})
  },
  // 获取验证码
  async handleWait() {
    try {
      await this.validateMoblie()
      await getCode(this.data.mobile)
      wx.showToast({
        title: '验证码发送成功',
        icon: 'success',
      })
      this.setData({'wait': 60})
      let timer = setInterval(() => {
        this.setData({'wait': this.data.wait - 1})
        if(this.data.wait === 0) clearInterval(timer)
      }, 1000);
    } catch (err) {
      console.log(err);
      wx.showToast({
        title: '发生错误',
        icon: 'error'
      })
    }
    
  },
  // 登陆
  async handleTap() {
    const obj = {mobile:this.data.mobile,code:this.data.code}
    try {
      this.validateMoblie()
      await this.validateCode()
      const { data } = await login(obj)
      wx.setStorage({
        key: 'my-token',
        data: data.token,
      });
      wx.showToast({
        title: '登陆成功',
        icon: 'success',
      });
      wx.switchTab({
        url: '/pages/user/user',
      });
    } catch (err) {
      wx.showToast({
        title: '登陆失败',
        icon: 'error',
      });
    }
  },
})